package com.xy.baselibrary.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.xy.baselibrary.R
import kotlinx.android.synthetic.main.base_fragment.*

/**
 * @ClassName BaseFragment
 * @Author xy
 * @Date 2021/7/23 11:18
 * @Description Fragment 基类 支持懒加载
 */
@Suppress("DEPRECATION")
abstract class BaseFragment : Fragment() {
    var viewIsCreated = false //view是否创建
    var currentVisibleState = false //当前界面是否可见
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.base_fragment, null)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val view = layoutInflater.inflate(setLayout(), null)
        ll.addView(
            view,
            ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        )
        viewIsCreated = true
        if (userVisibleHint) { //如果fragment可见
            loadData()
        }
        initData()
    }

    //不需要懒加载的时候使用
    open fun initData() {}

    abstract fun setLayout(): Int

    //加载数据
    open fun loadData() {}

    //停止加载数据
    open fun stopLoadData() {}


    //fragment是否可见 ，此方法比onCreate方法先执行，所以执行loadData方法时要先判断view是否创建
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        if (viewIsCreated) { //view创建了才有后续操作
            if (isVisibleToUser && !currentVisibleState) { //fragment可见且当前页不可见
                loadData()
            } else if (!isVisibleToUser && currentVisibleState) {
                stopLoadData()
            }
        }
        currentVisibleState = isVisibleToUser
    }

    override fun onPause() {
        super.onPause()
        currentVisibleState = false
    }

    override fun onDestroyView() {
        super.onDestroyView()
        viewIsCreated = false //view是否创建
        currentVisibleState = false //当前界面是否可见
    }


    override fun onResume() {
        super.onResume()
        if (userVisibleHint && !currentVisibleState) { //fragment可见且当前页不可见
            loadData()
        }
    }
}